/*
* Copyright 2017 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-service-dealer
*
* @File name : DealerService.java
*
* @Author : Administrator
*
* @Date : 2017年12月5日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2017年12月5日    Administrator    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/

package com.yonyou.gmmc.service.dealer.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.util.CheckUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yonyou.gmmc.service.dealer.constant.DealerConstant;
import com.yonyou.gmmc.service.dealer.dao.TmPositionMapper;
import com.yonyou.gmmc.service.dealer.dao.TmUsersMapper;
import com.yonyou.gmmc.service.dealer.dao.TrUserEnterpriseMapper;
import com.yonyou.gmmc.service.dealer.entity.UserInfoPO;
import com.yonyou.gmmc.service.dealer.model.TmPosition;
import com.yonyou.gmmc.service.dealer.model.TmUsers;
import com.yonyou.gmmc.service.dealer.model.TrUserEnterprise;

import tk.mybatis.mapper.entity.Example;

/**
 * @author Administrator
 * @date 2017年12月5日
 */
@Service
@Transactional
public class DealerService {

    private Logger                 logger = Logger.getLogger(DealerService.class);

    @Autowired
    private TmUsersMapper          tmUsersMapper;

    @Autowired
    private TmPositionMapper       tmPositionMapper;

    @Autowired
    private TrUserEnterpriseMapper trUserEnterpriseMapper;

    /**
     * 获取人员信息
     * 
     * @author Administrator
     * @date 2017年12月21日
     * @param userId
     * @param phone
     * @return
     * @throws Exception
     */
    public List<TmUsers> userInfo(String userId, String phone, String name, String avatar) throws Exception {
        List<TmUsers> resultList = new ArrayList<TmUsers>();
        try {
            Example example = new Example(TmUsers.class);
            example.createCriteria().andCondition("PHONE=", phone);
            resultList = tmUsersMapper.selectByExample(example);
            if (resultList.size() == 0) {
                return resultList;
            } else {
                example.createCriteria().andCondition("WX_USER_ID=", userId);
                int count = trUserEnterpriseMapper.selectCountByExample(example);
                if (count > 0) {
                    return resultList;
                } else {
                    logger.info("新增一条绑定关系");
                    TrUserEnterprise record = new TrUserEnterprise();
                    record.setUserId(resultList.get(0).getUserId().toString());
                    record.setPhone(phone);
                    record.setWxUserId(userId);
                    if (!CheckUtil.NullOrEmpty(avatar)) {
                        record.setIconsPhone(avatar);
                    }
                    if (!CheckUtil.NullOrEmpty(name)) {
                        record.setWeixinName(name);
                    }
                    record.setUpdateDate(new Date());
                    record.setUpdateBy(DealerConstant.CREATE_USER);
                    int a = trUserEnterpriseMapper.insertSelective(record);
                    if (a == 1) {
                        return resultList;
                    } else {
                        resultList.removeAll(resultList);
                        return resultList;
                    }
                }
            }
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    public Map<String, Object> users(UserInfoPO userInfo) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            TmUsers record = new TmUsers();
            record.setPhone(userInfo.getMobile());
            List<TmUsers> list = tmUsersMapper.select(record);
            record.setUserName(userInfo.getName());
            record.setDealerCode(userInfo.getDepartment());
            record.setIconsPhoto(userInfo.getAvatar());
            record.setSex(Short.valueOf(userInfo.getGender()));
            if (!CheckUtil.NullOrEmpty(userInfo.getEmail())) {
                record.setEmial(userInfo.getEmail());
            }
            record.setStatus((short) 1);
            if (list.size() == 0) {
                logger.info("该成员为新增成员，新增信息");
                record.setCreateDate(new Date());
                record.setCreateBy(DealerConstant.CREATE_USER);
                record.setLoginName(userInfo.getMobile());// 初始登录名为手机号
                String passWord = "21232f297a57a5a743894a0e4a801fc3";// 初始密码admin
                record.setPassword(passWord);
                int a = tmUsersMapper.insertSelective(record);
                if (a == 1) {
                    logger.info("新增成员信息成功，进行职位-成员绑定关系处理");
                    String userId = tmUsersMapper.selectUserIdByPhone(userInfo.getMobile());
                    boolean flag = queryPosition(userId, userInfo.getPosition());
                    if (flag) {
                        resultMap.put("errorCode", 200);
                        resultMap.put("errorMsg", "新增成员成功");
                    } else {
                        resultMap.put("errorCode", 500);
                        resultMap.put("errorMsg", "更新成员失败");
                    }
                } else {
                    resultMap.put("errorCode", 500);
                    resultMap.put("errorMsg", "更新成员失败");
                }
            } else {
                logger.info("该成员为已存在成员，更新信息");
                Example example = new Example(TmUsers.class);
                example.createCriteria().andCondition("PHONE=", userInfo.getMobile());
                record.setUpdateDate(new Date());
                record.setUpdateBy(DealerConstant.UPDATE_USER);
                int a = tmUsersMapper.updateByExampleSelective(record, example);
                if (a == 1) {
                    logger.info("更新成员信息成功，进行职位-成员绑定关系处理");
                    String userId = tmUsersMapper.selectUserIdByPhone(userInfo.getMobile());
                    boolean flag = queryPosition(userId, userInfo.getPosition());
                    if (flag) {
                        resultMap.put("errorCode", 200);
                        resultMap.put("errorMsg", "更新成员成功");
                    } else {
                        resultMap.put("errorCode", 500);
                        resultMap.put("errorMsg", "更新成员失败");
                    }
                } else {
                    resultMap.put("errorCode", 500);
                    resultMap.put("errorMsg", "更新成员失败");
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
        return resultMap;
    }

    /**
     * 对成员职位进行处理
     * 
     * @author Administrator
     * @date 2017年12月6日
     * @param phone
     * @param position
     * @return
     */
    public boolean queryPosition(String userId, String position) {
        logger.info("先判断该职位是否已存在");
        String positionId = tmPositionMapper.selectPositionByName(position);
        if (CheckUtil.NullOrEmpty(positionId)) {
            logger.info("该职位不存在，需新增职位");
            TmPosition record = new TmPosition();
            record.setCreateDate(new Date());
            record.setPositionName(position);
            record.setStatus(1011);
            int a = tmPositionMapper.insertSelective(record);
            if (a == 0) {
                logger.info("新增职位失败");
                return false;
            }
            positionId = tmPositionMapper.selectPositionByName(position);
        }
        String positionRelationId = tmPositionMapper.selectRelationByUserId(userId);
        if (CheckUtil.NullOrEmpty(positionRelationId)) {
            logger.info("该成员不存在职位绑定关系，需新增一条绑定记录");
            int a = tmPositionMapper.insertRelation(userId, position);
            if (a == 0) {
                logger.info("绑定职位失败");
                return false;
            }
            return true;
        } else {
            if (!positionId.equals(positionRelationId)) {
                logger.info("该成员职位与绑定职位不同，新增一个职位绑定关系");
                int a = tmPositionMapper.insertRelation(userId, position);
                if (a == 0) {
                    logger.info("绑定职位失败");
                    return false;
                }
                return true;
            } else {
                logger.info("该成员职位与绑定职位相同，不作处理");
                return true;
            }
        }
    }
}
